package com.hzyb.config;

import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * @author 19516
 * 文件服务器配置类
 * 2018-02-01
 * 单振龙
 */

@Configuration
public class Config extends WebMvcConfigurerAdapter {
    //获取配置文件中图片的路径
    @Value("${hzyb.imagesPath}")
    private String mImagesPath;
    //图片虚拟根目录
    @Value("${picture.virtual.rootPath}")
    private String pictureVirtualRootPath;

    //访问图片方法
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        if (mImagesPath.equals("") || mImagesPath.equals("${hzyb.imagesPath}")) {
            String imagesPath = Config.class.getClassLoader().getResource("").getPath();
            if (imagesPath.indexOf(".jar") > 0) {
                imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));
            } else if (imagesPath.indexOf("classes") > 0) {
                imagesPath = "file:" + imagesPath.substring(0, imagesPath.indexOf("classes"));
            }
            imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/")) + "/images/";
            mImagesPath = imagesPath;
        }
        LoggerFactory.getLogger(Config.class).info("imagesRealPath=" + mImagesPath);
        LoggerFactory.getLogger(Config.class).info("imagesVirtualPath=" + pictureVirtualRootPath);
        registry.addResourceHandler(pictureVirtualRootPath).addResourceLocations(mImagesPath);
        super.addResourceHandlers(registry);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        // TODO Auto-generated method stub
        registry.addInterceptor(new RequestLog()).addPathPatterns("/**");
    }
}